package com.base.cn.platform.os.common.thread;

import com.base.cn.platform.os.common.filter.RequestData;

import java.util.concurrent.Callable;

/**
 * 切换线程时下下文回调
 *
 * @author s.li
 * @date 2019/05/09
 */
public class ContextAwareCallable<T> implements Callable<T> {
    private Callable<T> task;
    private RequestData requestData;

    public ContextAwareCallable(Callable<T> task, RequestData requestData){
        this.task = task;
        this.requestData = requestData;
    }

    @Override
    public T call() throws Exception {
        //如果原有的上下文对象不为空
        if(requestData !=null){
            //把原有线程的上下文对象传递给下一个线程
            RequestData.requestDataThreadLocal.set(requestData);
        }
        try {
            return task.call();
        }finally {
            RequestData.requestDataThreadLocal.remove();
        }
    }
}
